from datetime import datetime
from typing import Any

import pydantic
from pydantic import Field, ConfigDict
from starlette import status
from starlette.responses import PlainTextResponse

from app.core.code_msg import CodeMsg


class BaseModel(pydantic.BaseModel):
    model_config = ConfigDict(
        # str_strip_whitespace=True, # 不建议配置此项
        use_enum_values=True,
        arbitrary_types_allowed=True,
        json_encoders={
            datetime: lambda v: v.strftime("%Y-%m-%d %H:%M:%S")
        },
    )


class R(BaseModel):
    code: int = Field(title="响应码")
    message: str | None = Field(title="响应消息")
    data: Any = Field(default=None, title="响应体")

    @staticmethod
    def ok(code=0, message="操作成功", data: Any = None):
        return PlainTextResponse(
            status_code=status.HTTP_200_OK,
            media_type="application/json",
            content=R(code=code, message=message, data=data).model_dump_json(),
        )

    @staticmethod
    def fail(*, code_msg: CodeMsg = None, code: int = -1, message: str = "操作失败",
             data: Any = None):
        if code_msg:
            return PlainTextResponse(
                status_code=status.HTTP_200_OK,
                media_type="application/json",
                content=R(code=code_msg.code, message=code_msg.message, data=data).model_dump_json()
            )
        return PlainTextResponse(
            status_code=status.HTTP_200_OK,
            media_type="application/json",
            content=R(code=code, message=message, data=data).model_dump_json()
        )


class BasePageReq(BaseModel):
    page_num: int = Field(default=1, gt=0, description="页码")
    page_size: int = Field(default=10, gt=0, description="每页记录数")


class BaseDto(BaseModel):
    user_id: str = Field(max_length=64, description="用户id", )
    user_name: str = Field(max_length=64, description="用户名", )
